<?php
/**
 * Import Files to initialise contact creation
 * In this screen, you are able to import xls or csv
 * file containing contact list
 * 
 * @author Xavier VILAIN
 * @package Hive\Ressource
 * @license #license#
 * 
 */

use Hive\Ressource\Address;
use Doctrine\DBAL\Connection;
use Orx\Etl\Extractor;
use Hive\Company;
use Fox\Grid\FieldCat\Field\Renderer\Anchor;
use Fox\Grid\FieldCat\Field;
use Hive\Ressource\Experience;
use Hive\Ressource;
use Fox\Html\Input;
use Fox\Generator;
use Fox\Html\Input\File;
use Fox\Html\Block;
use Fox\Html\DropList;
use Fox\Html\Screen;
use Fox\Html\Button\Help;
use Fox\Html\CheckBox;

$xview = Xview::instance();
$customizing = Hive\Customizing::instance();

$screen = new Screen('sImportContacts','import');
$screen->pageTitle(Msg(Hive::BUNDLE,Hive::TITLE_IMPORT_CONTACTS));
$block = new Block('bImportContacts');
// Contact Groups
if($customizing->hasGroup()) {
	$groupingDp = $xview->component('ressource','grouping',array('authorizationCheck' => true));
	$block->add($groupingDp);
}

// Format du fichier
$fileFormats = Fox\Dao::finder(Extractor::className())
				->follow(Hive\Contact\Extractor::LINK_CONTACT_EXTRACTORS)
				->find();
$block->add(new DropList('h_file_format',true,false,true))
		->options($fileFormats,'extractor',Generator::call('label'));
$sourcesDp = $xview->component('ressource','sources');
$block->add($sourcesDp);
// Filename
$block->add(new File('filename',true))
		->filter(array('csv','xls','xlsx'))
		;
$block->add(new Input('serverfilename'))->hidden();
// Test Mode
$block->add(new CheckBox('itest',true))
		->label(Msg(Hive::BUNDLE,Hive::IMPORT_TEST_MODE))
		->add(new Help('testmodeHelp',Msg(Hive::BUNDLE,Hive::IMPORT_TEST_MODE_HELPER)));
// Options - Update Existing
/*
$block->add(new CheckBox('updexisting',false))
		->add(new Help('updexistingHelp',Msg(Hive::BUNDLE,Hive::IMPORT_UPDATE_EXISITING_HELPER)));
$block->item('updexisting')->label(Msg(Hive::BUNDLE,Hive::IMPORT_UPDATE_EXISITING));
*/
$block->labelSize(250,true);
$screen->add($block);
if(Hive\Customizing::instance()->isDemo()) {
	
	Hive\Customizing::instance()->demonstrationErrorMessage();
	$screen->displayMode(Screen::DISPLAY_READONLY,true);
}
if($screen->submitted()) {
	
	$fields = $screen->get();
	if(!$screen->errors()) {
		
		// Load Expected Format
		$extractor = Fox\Dao::load(Extractor::className(),$fields['h_file_format']);
		$block->item('filename')->filter(array($extractor->attribute('extensions')));
		$fields = $screen->get();
	}
	if(!$screen->errors()) {
		// Message Types
		$typeSucess = Msg(\Fox\Msg::BUNDLE,\Fox\Msg::SUCCESS);
		$typeError = Msg(\Fox\Msg::BUNDLE,\Fox\Msg::ERROR);
		$typeWarning = Msg(\Fox\Msg::BUNDLE,\Fox\Msg::BLOCK);
		// Available Fields 
		$experienceInformation = false;
		$professionnalAddress = false;
		
		$fields['updexisting'] = false;
		// Copy File inside the server
		$fileData = Xview::moveFileToServer();
		$fileName = $fileData['destination'];
		$data = $extractor->readFile($fileName);
		unlink($fileName);// Delete the file no need to keep it
		if($fields['itest']) {
			$commit = false;
		} else {
			$commit = true;
		}
		// Contact Grouping
		$grouping = !empty($fields['grouping']) ? $fields['grouping'] : 1;
		$infos = Fox\Dao::infos(Ressource::className());
		// Load All references
		foreach($extractor->references as $tabix => $reference) {
			$contact = null;
			if(!empty($reference[Ressource::REFERENCE_UPLOAD])) {
				$contact = new Ressource();
				$contactData = $reference[Ressource::REFERENCE_UPLOAD][1];
				$contact->setFields($contactData);
				$contact->grouping = $grouping;
				//$query = $infos->handle()->createQueryBuilder();
				$emails = null;
				
				if(!empty($contactData['email'])) {
					$emails[] = strtolower(trim($contactData['email']));
				}
				if(!empty($contactData['email1'])) {
					$emails[] =  strtolower(trim($contactData['email1']));
				}
				if(!empty($contactData['email2'])) {
					$emails[] = strtolower(trim($contactData['email2']));
				}
				if(empty($emails)) {
					$msg = Msg(Hive::BUNDLE,Hive::ERR_EMAIL_NOT_FOUND);
					Fox\Message::Error($msg);
					$data[$tabix]['type'] = $typeError;
					$data[$tabix]['msg'] = $msg;
					continue;
				} else {
					
					$result = Ressource::findEmailDuplicates($emails);
				}
				$nbResult = count($result);
				if($nbResult > 0) 
				{
					// Check Unicity
					if(!$fields['updexisting'] || $nbResult > 1) {
						$msg = Msg(Hive::BUNDLE,Hive::ERR_EMAIL_ALREADY_USED_BY,
								$result[0]['email'],
								$result[0]['first_name'].' '.$result[0]['last_name']);
						Fox\Message::Warning($msg);
						$data[$tabix]['type'] = $typeWarning;
						$data[$tabix]['msg'] = $msg;
						$data[$tabix]['rid'] = $result[0]['ressource_id'];
						continue;
					}
				}
			}
			// Import Professionnal Address
			if(!empty($reference[Address::REFERENCE_PROFESSIONAL]) && !empty($contact)) {
				$professionnalAddress = true;
				foreach($reference[Address::REFERENCE_PROFESSIONAL] as $proData) {
					$contact->additionnalAddresses($proData);
				}
			}
			if(!empty($reference[Experience::REFERENCE_UPLOAD]) && !empty($contact)) {
				$experienceInformation = true;
				foreach($reference[Experience::REFERENCE_UPLOAD] as $experienceData) {
					$experience = new Experience();
					if(!empty($experienceData['company'])) {
						$companyName = $experienceData['company'];
						// Company Creation
						if(empty($companies[$companyName])) {
							$company = Company::lookup($companyName);
							if(!$company)
							{
								$company = new Company();
								$company->setFields(array('company_name' =>$companyName));
								$company->create();
							}
							$companies[$companyName] = $company->getId();
						}
						$experienceData['compid'] = $companies[$companyName];
					}
					if(empty($experienceData['start_date'])) {
						$experienceData['start_date'] = '1900-01-01';//@TODO fix this will a real rule
					}
					$experienceData['current'] = 1;
					if(!empty($experienceData['jobtitle'])) {
						$experience->setFields($experienceData);
						$contact->addToExperiences($experience);
					}
					unset($experience);
				}
			}
			try {
				if($contact->exists()) {
					$updateMsg = Msg(Fox\Msg::BUNDLE,Fox\Msg::MSG_UPDATE,$contact->email);
					$data[$tabix]['msg'] = $updateMsg;
					$data[$tabix]['rid'] = $contact->getId();
					$data[$tabix]['type'] = $typeSucess;
					// Update Existing Contact ?
					if($fields['updexisting'] && $commit) {
						//	$contact->update();
						Fox\Message::Success($updateMsg);
					}
					
				} else {
					$email = $contact->email;
					if(empty($email)) {
						$contact->email = $contact->email1;
						$contact->address()->email1 = null;
					}
					$creationMsg = Msg(Fox\Msg::BUNDLE,Fox\Msg::MSG_CREATE,$contact->email);
					$data[$tabix]['msg'] = $creationMsg;
					$data[$tabix]['type'] = $typeSucess;
					if($commit) {
						$contact->create();
						$data[$tabix]['rid'] = $contact->getId();
						Fox\Message::Success($creationMsg);
					}
				}
			} catch(Fox\Object\Exception\Save $e){
				$data[$tabix]['msg'] = $e->getMessage();
				Fox\Message::Error($e->getMessage());
			}
			unset($contact);
		}
		// Build output grid
		//$grid = $extractor->outputGrid();
		$grid = new Fox\Grid('gFinalResult',null,Msg(Hive::BUNDLE,Hive::CONTACT_IMPORT_RESULT_GRID ));
		$grid->fieldcat(array(array('first_name','1_1_first_name'),
							array('last_name','1_1_last_name'),
							array('gender','1_1_gender'),
							array('birth_date','1_1_birth_date'),
							array('email','1_1_email'),
							array('jobtitle','2_1_jobtitle'),
							array('company','2_1_company'),
							array('street','1_1_street'),
							array('postal_code','1_1_postal_code'),
							array('city','1_1_city'),
							array('country','1_1_country'),
							array('email1','1_1_email1'),
							array('phone1','1_1_phone1'),
							array('phone2','1_1_phone2'),
							array('street','3_2_street'),
							array('postal_code','3_2_postal_code'),
							array('city','3_2_city'),
							array('country','3_2_country'),
							array('email1','3_2_email1'),
							array('phone1','3_2_phone1'),
							array('phone2','3_2_phone2')
							));
		$grid->fieldcat()->field('1_1_country')->noConversion();
		$grid->fieldcat()->field('3_2_country')->noConversion();
		// Basic Information
		$groupingField = new Field('contact_information');
		$groupingField->setClass("gd-col-group separator-left");
		$grid->fieldcat()->buildSubTitleByGrouping(array(
					'1_1_first_name',
					'1_1_last_name',
					'1_1_gender',
					'1_1_birth_date',
					'1_1_email'), $groupingField);
		$grid->fieldcat()->field('1_1_email')->setClass("separator-right");
		// Job Information
		$groupingField = new Field('job_information');
		$groupingField->headerAlign('center');
		$groupingField->setClass("gd-col-group separator-left");
		$grid->fieldcat()->buildSubTitleByGrouping(array(
					'2_1_jobtitle',
					'2_1_company'), $groupingField);
		$grid->fieldcat()->field('2_1_jobtitle')->setClass("separator-left");
		// Personnal Address
		$groupingField = new Field('personal_address');
		$groupingField->setClass("gd-col-group separator-left");
		$grid->fieldcat()->buildSubTitleByGrouping(array(
					'1_1_street',
					'1_1_postal_code',
					'1_1_city',
					'1_1_country',
					'1_1_email1',
					'1_1_phone1',
					'1_1_phone2'), $groupingField);
		$grid->fieldcat()->field('1_1_street')->setClass("separator-left");
		// Professionnal Address
		if($professionnalAddress) {
			$groupingField = new Field('professional_address');
			$groupingField->setClass("gd-col-group separator-left");
			$grid->fieldcat()->buildSubTitleByGrouping(array(
						'3_2_street',
						'3_2_postal_code',
						'3_2_city',
						'3_2_country',
						'3_2_email1',
						'3_2_phone1',
						'3_2_phone2'), $groupingField);
			$grid->fieldcat()->field('3_2_street')->setClass("separator-left");
		} else {
			$grid->fieldcat()->setFieldAttr(array(
						'3_2_street',
						'3_2_postal_code',
						'3_2_city',
						'3_2_country',
						'3_2_email1',
						'3_2_phone1',
						'3_2_phone2'),'hidden',true);
		}
		$grid->fieldcat()->add(new Field(array('message_type','type')))->setNoWrap();
		$grid->fieldcat()->add(new Field(array('message','msg')));
		$grid->fieldcat()->field('type')->setClass("separator-left");
		$grid->fieldcat()->field('msg')->renderers(new Anchor(
			Fox\Generator::url('ressource','main',null,array('rid' => Generator::useElement('rid'))),
			true
		));
		$grid->layout()
				->zebra(false)
				->scrollHorizontal(true)
				->styleGenerator(Generator::useFunction(function($data) use ($typeSucess,$typeWarning,$typeError) {
			switch($data['type']) {
				case $typeSucess: 
					return 'background-color:#dff0d8;';
					break;
				case $typeWarning: 
					return 'background-color:#fbeed5;';
					break;
				case $typeError: 
					return 'background-color:#eed3d7;';
					break;	
			}
		}));
		$grid->setXlsDownload();
		
		// Display Data
		$grid->initialize($data);
		
	}
}
echo $screen->display();
if(isset($grid))
	echo $grid->display();